import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin

class WeightedMajorityClassifier(BaseEstimator, ClassifierMixin):
    def __init__(self, base_estimators, beta=0.5):
        self.base_estimators = base_estimators
        self.beta = beta
        self.weights = None
        
    def fit(self, X, y):
        n_estimators = len(self.base_estimators)
        self.weights = np.ones(n_estimators)
        
        # 训练所有基学习器
        for estimator in self.base_estimators:
            estimator.fit(X, y)
        return self
    
    def predict(self, X):
        predictions = np.array([estimator.predict(X) for estimator in self.base_estimators])
        weighted_votes = np.dot(self.weights, predictions)
        return np.where(weighted_votes >= 0, 1, 0)
    
    def partial_fit(self, X, y):
        """在线学习：根据新数据更新权重"""
        if self.weights is None:
            self.weights = np.ones(len(self.base_estimators))
            
        # 获取当前预测
        current_predictions = self.predict(X)
        
        # 更新权重
        for i, estimator in enumerate(self.base_estimators):
            estimator_prediction = estimator.predict(X)
            if estimator_prediction != y:
                self.weights[i] *= self.beta
                
        # 归一化权重
        self.weights /= np.sum(self.weights)
        return self